﻿using LotusIslandOrderProcessing.model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;

namespace LotusIslandOrderProcessing.PLCMake
{
    public class HttpClient
    {
        public static string url_start = "https://" + IPorPortInfo.Instance.CoffeeIP + "/api/jsonrpc";

        //public static string url_start = "https://" + IPorPortInfo.Instance.CoffeeIP + "/";
        private static HttpClient instance;
        private HttpClient() { }
        public static HttpClient Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new HttpClient();
                }
                return instance;
            }
        }
        //public string Login()
        //{
        //    Thread.Sleep(1500);
        //    jsonParam1 = "[{\"jsonrpc\":\"2.0\",\"method\":\"Api.Login\",\"params\":{\"user\":\"admin\",\"password\":\"123456\"},\"id\":999}]";
        //    return ClientRequest(_url, jsonParam1);
        //}
        public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {   // 总是接受  
            return true;
        }
        public string ServerGet(string url, string url_start = "https://192.168.5.102/api/jsonrpc")
        {
            string result = string.Empty;
            try
            {
                url = url_start + url;
                HttpWebRequest request = null;
                request = WebRequest.Create(url) as HttpWebRequest;
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request.ProtocolVersion = HttpVersion.Version11;
                // 这里设置了协议类型。
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; ;// SecurityProtocolType.Tls1.2;
                request.KeepAlive = false;
                ServicePointManager.CheckCertificateRevocationList = true;
                ServicePointManager.DefaultConnectionLimit = 100;
                ServicePointManager.Expect100Continue = false;

                request.Method = "GET"; //使用get方式发送数据
                request.ContentType = "application/json";
                request.Accept = "application/json";
                request.Referer = null;
                request.AllowAutoRedirect = true;

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream stream = response.GetResponseStream();
                using (StreamReader sr = new StreamReader(stream))
                {
                    result = sr.ReadToEnd();
                }
                //Console.Write(result);
                return result;
            }
            catch (Exception)
            {
                return result;
            }
        }
        private static bool RemoteCertificateValidate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
        {
            return true;
        }
        public string HttpPostRaw(string url, string data, string url_start, bool bol = false)
        {
            string value = "";
            try
            {
                string realurl = url_start + url;
                HttpWebRequest reqest = (HttpWebRequest)WebRequest.Create(realurl);
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                reqest.ProtocolVersion = HttpVersion.Version11;
                // 这里设置了协议类型。
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; ;// SecurityProtocolType.Tls1.2;
                reqest.KeepAlive = false;
                ServicePointManager.CheckCertificateRevocationList = true;
                ServicePointManager.DefaultConnectionLimit = 100;
                ServicePointManager.Expect100Continue = false;
                reqest.Method = "POST";
                reqest.ContentType = "application/json";
                if (bol)
                    reqest.Timeout = 3000;
                while (true)
                {
                    try
                    {
                        var tokenlist = HttpPostRawtoken("", "[{\"jsonrpc\":\"2.0\",\"method\":\"Api.Login\",\"params\":{\"user\":\"admin\",\"password\":\"123456\"},\"id\":999}]");
                        if (tokenlist != "")
                        {
                            try
                            {
                                var token = JsonConvert.DeserializeObject<List<GetToken>>(tokenlist);
                                if (token != null)
                                {
                                    if (token[0].result != null)
                                    {

                                        reqest.Headers.Add("X-Auth-Token", token[0].result.token);
                                        break;
                                    }
                                }
                            }
                            catch (Exception)
                            {
                                continue;
                            }
                        }
                        Thread.Sleep(500);
                    }
                    catch (Exception)
                    {
                        continue;
                    }

                }
                Stream stream = reqest.GetRequestStream();
                byte[] bs = System.Text.Encoding.UTF8.GetBytes(data);
                stream.Write(bs, 0, bs.Length);
                stream.Flush();
                stream.Close();
                ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;
                HttpWebResponse response = (HttpWebResponse)reqest.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                value = sr.ReadToEnd();
                response.Close();
                return value;
            }
            catch (Exception ex)
            {
                return "";
            }
        }
        //string url_start= "https://192.168.5.102/api/jsonrpc"
        public string HttpPostRawlist(string url, string data, string url_start, bool bol = false)
        {
            string value = "";
            try
            {
                string realurl = url_start + url;
                HttpWebRequest reqest = (HttpWebRequest)WebRequest.Create(realurl);
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                reqest.ProtocolVersion = HttpVersion.Version11;
                // 这里设置了协议类型。
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; ;// SecurityProtocolType.Tls1.2;
                reqest.KeepAlive = false;
                ServicePointManager.CheckCertificateRevocationList = true;
                ServicePointManager.DefaultConnectionLimit = 100;
                ServicePointManager.Expect100Continue = false;
                reqest.Method = "POST";
                reqest.ContentType = "application/json";
                if (bol)
                    reqest.Timeout = 2000;
                Stream stream = reqest.GetRequestStream();
                byte[] bs = System.Text.Encoding.UTF8.GetBytes(data);
                stream.Write(bs, 0, bs.Length);
                stream.Flush();
                stream.Close();
                ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;
                HttpWebResponse response = (HttpWebResponse)reqest.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                value = sr.ReadToEnd();
                response.Close();
                return value;
            }
            catch (Exception ex)
            {
                return "";
            }
        }
        public string HttpPostRawtoken(string url, string data)
        {
            string value = "";
            try
            {
                string realurl = "https://" + IPorPortInfo.Instance.CoffeeIP + "/api/jsonrpc" + url;
                HttpWebRequest reqest = (HttpWebRequest)WebRequest.Create(realurl);
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                reqest.ProtocolVersion = HttpVersion.Version11;
                // 这里设置了协议类型。
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; ;// SecurityProtocolType.Tls1.2;
                reqest.KeepAlive = false;
                ServicePointManager.CheckCertificateRevocationList = true;
                ServicePointManager.DefaultConnectionLimit = 100;
                ServicePointManager.Expect100Continue = false;
                reqest.Method = "POST";
                reqest.ContentType = "application/json";
                Stream stream = reqest.GetRequestStream();
                byte[] bs = System.Text.Encoding.UTF8.GetBytes(data);
                stream.Write(bs, 0, bs.Length);
                stream.Flush();
                stream.Close();
                ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;
                HttpWebResponse response = (HttpWebResponse)reqest.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                value = sr.ReadToEnd();
                response.Close();
                return value;
            }
            catch (Exception ex)
            {
                // error = ex.ToString();
                return "";
            }
        }
        public void HttpPost(string Url, string postDataStr)
        {
            //string realurl = url_start + Url;
            //CoffeeProductID ceshi = new CoffeeProductID();
            //ceshi.productId = postDataStr;
            //string json = JsonConvert.SerializeObject(ceshi);
            //  HttpPostRaw(Url, postDataStr);

        }
    }
}
